<template>
  <a-card :bordered="false">
    <!-- <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="角色名称">
              <a-input v-model="queryParam.keyword" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select placeholder="请选择" default-value="0">
                <a-select-option value="-1">全部</a-select-option>
                <a-select-option value="0">正常</a-select-option>
                <a-select-option value="1">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
            <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div> -->

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
    </div>
    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="true"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="status" slot-scope="text,record">
        <a-switch v-model="record.status" @change="handleSwitchChange(record.id,record.status)" />
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)"><a-icon type="edit"/></a>
          <a-divider type="vertical" />
          <a @click="handleDeleteOk(record.id)"><a-icon type="delete"/></a>
          <a-divider type="vertical" />
          <a @click="handleRoleOk(record)"><a-icon type="bars"/></a>
        </template>
      </span>
    </s-table>

    <!-- <role-modal ref="modal" @ok="handleOk"></role-modal> -->
    <create-form
        ref="createModal"
        :title="title"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <role-modal
        ref="modal"
        :title="title2"
        :visible="visible2"
        :loading="confirmLoading2"
        :model="mdl2"
        :treeValue="treeValue"
        @cancel="handleCancel2"
        @ok="handleOk2"
      />
  </a-card>
</template>

<script>
import { STable } from '@/components'
import RoleModal from './modules/RoleMeen'
import CreateForm from './modules/CreateRole'
import { getList, updateStatus,createRole,updateRole } from '@/api/role'
import { deleteRole, getRoleMenu } from '@/api/system'
import { deleteDevice } from '@/api/device'
export default {
  name: 'TableList',
  components: {
    STable,
    RoleModal,
    CreateForm
  },
  data () {
    return {
      description: '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      visible: false,
      title:'',

      form: null,
      mdl: {},
      // create model
      title2:'',
      visible2: false,
      confirmLoading2: false,
      mdl2: null,
      treeValue:[],

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: 'id',
          dataIndex: 'id'
        },
        {
          title: '角色名称',
          dataIndex: 'name',
          width: 300
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '描述',
          dataIndex: 'description',
          width: 300
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          sorter: true
        }, {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getList(requestParameters)
          .then(res => {
            const data = res.data
            console.log('data',data)
            data.list.forEach(element => {
              element.status = element.status == 0
            })
            return data
          })
      },

      selectedRowKeys: [],
      selectedRows: []
    }
  },
  watch:{
    visible2(newValue){
      this.visible2=newValue
    }
  },
  methods: {
    handleDeleteOk(id) {
      var that = this
      this.$confirm({
        title: '确认要删除吗',
        onOk() {
          deleteRole(id).then(res => {
            if (res.code == 200) {
              // 刷新表格
              that.$refs.table.refresh(true)
              that.$message.info('删除成功')
            } else {
              that.$message.error(res.message)
            }
          })
        },
        onCancel() {
        }
      })
    },
    handleCancel2(){

    },
    handleOk2(){

    },
    handleRoleOk(record){
      var _this=this
      _this.visible = false
      _this.visible2 = true
      // _this.treeValue=[7,8,9,10,11]
      _this.title2='分配菜单'
      _this.mdl2 = { ...record }
      getRoleMenu(record.id).then(res=>{
        _this.treeValue=[]
        res.data.forEach((element)=>{
          if(_this.treeValue.indexOf(element.id)==-1)
            _this.treeValue.push(element.id)
          if(element.children.length>0){
            element.children.forEach((k)=>{
              if(_this.treeValue.indexOf(k.id)==-1)
                _this.treeValue.push(k.id)
            })
          }
        })
        console.log('this.treeValue',_this.treeValue)
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleAdd () {
      this.mdl = null
      this.title='添加角色'
      this.visible = true
      this.visible2 = false
    },
    handleSwitchChange (id, status) {
      // 处理 Switch 状态改变的事件逻辑，例如更新数据源中的状态值等。
      var key = status == true ? 0 : 1
      updateStatus(id, key).then((res) => {
        this.$refs.table.refresh()
      })
      // const updatedDataSource = this.loadData.map((item) => {
      //   if (item.id === key) {
      //     item.status = !item.status; // 切换状态值
      //   }
      //   return item;
      // });
      // this.loadData = updatedDataSource; // 更新数据源
    },
    handleEdit (record) {
      this.mdl = Object.assign({}, record)
      console.log(this.mdl)
      this.visible = true
      this.visible2 = false
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            updateRole(values,values.id).then(res => {
              console.log('res', res)
              this.confirmLoading = false
              // 刷新表格
              this.$refs.table.refresh()
              if (res.code == 200) {
                // 重置表单数据
                this.visible = false
                this.visible2 = false
                form.resetFields()
                this.$message.info('修改成功')
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            // 新增
            createRole(values).then(res => {
              console.log('res', res)
              this.confirmLoading = false
              // 刷新表格
              this.$refs.table.refresh()
              if (res.code == 200) {
                // 重置表单数据
                this.visible = false
                form.resetFields()
                this.$message.info('新增成功')
              } else {
                this.$message.error(res.message)
              }
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>
